import { getToken, getAppChannel, goTo } from './common'
import qs from 'qs'

interface RequestOptions extends UniNamespace.RequestOptions, RequestOptions { }

class Request {
	private baseUrl : string

	private config : RequestOptions = {
		url: '',
		header: {}
	}

	constructor() {
		this.baseUrl = import.meta.env.VITE_APP_BASE_URL.substr(-1) == '/' ? import.meta.env.VITE_APP_BASE_URL : `${import.meta.env.VITE_APP_BASE_URL}/`;

		try {
			this.config.header[import.meta.env.VITE_REQUEST_HEADER_CHANNEL_KEY] = getAppChannel()
		} catch (e) { }

	}

	/**
	 * 请求拦截器
	 */
	private requestInterceptors() {
		// 携带token
		try {
			getToken() && (this.config.header[import.meta.env.VITE_REQUEST_HEADER_TOKEN_KEY] = "Bearer " + getToken())
			this.config.header[import.meta.env.VITE_REQUEST_HEADER_CHANNEL_KEY] = getAppChannel()
		} catch (e) {
		}
	}

	public get(url : string, data : AnyObject = {}) {
		return this.request('GET', url, data)
	}

	public post(url : string, data : AnyObject = {}) {
		return this.request('POST', url, data)
	}

	public put(url : string, data : AnyObject = {}) {
		return this.request('PUT', url, data)
	}

	public delete(url : string) {
		return this.request('DELETE', url, {})
	}

	/**
	 * 发送上传请求
	 */
	public upload(url : string, data : AnyObject = {}) {
		this.requestInterceptors()

		const params = {
			url: this.baseUrl + url,
			...data
		};

		return new Promise((resolve, reject) => {
			uni.uploadFile({
				...params,
				success: (res : any) => {
					const data = JSON.parse(res.data)
					if (data.code == 200) {
						resolve(data)
					} else {
						reject(data)
					}
				},
				fail: (res : any) => {
					reject(res)
				}
			})
		})
	}
	public isArray(value : any) {
		if (typeof Array.isArray === 'function') {
			return Array.isArray(value)
		}
		return Object.prototype.toString.call(value) === '[object Array]'
	}
	/**
	 * 深度拷贝对象
	 * @param {Object} obj
	 */
	public deepClone(obj : any) {
		// 对常见的“非”值，直接返回原来值
		if ([null, undefined, NaN, false].includes(obj)) return obj
		if (typeof obj !== 'object' && typeof obj !== 'function') {
			// 原始类型直接返回
			return obj
		}
		const o = this.isArray(obj) ? [] : {}
		for (const i in obj) {
			if (obj.hasOwnProperty(i)) {
				o[i] = typeof obj[i] === 'object' ? this.deepClone(obj[i]) : obj[i]
			}
		}
		return o
	}
	/**
	 * 发送请求
	 */
	private request(method : string, url : string, data ?: AnyObject) {
		this.requestInterceptors()

		const params = Object.assign(this.deepClone(this.config), {
			url: this.baseUrl + url,
			method
		})
		if (params.method.toUpperCase() == 'GET') {
			params.url += '?' + qs.stringify(data);
		} else {
			params.data = data;
		}

		return new Promise((resolve, reject) => {
			uni.request({
				...params,
				success: (res : any) => {
					const data = res.data
					if (data.code == 200 || data.code == -100 || data.code == 0 || data.code == 600) {
						resolve(data)
					} else {
						// reject(data)
						resolve(data)
					}
				},
				fail: (res : any) => {
					reject(res)
				},
				complete: (res : any) => {
					// console.log(res)
				}
			})
		})
	}
}

export default new Request()